<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {useRouter} from 'vue-router';
import {findAllTablesApi, findSelectDatasourceListApi} from "@/api/datasource";
import type {ColumnInfo, DbTable, GlobalDataSource} from "@/api/datasource/type.ts";
import {ElMessage} from "element-plus";
import type {Page} from "@/api/common-types.ts";
import {DB_HEADER} from "@/api/common-types.ts";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import {genCodeByTableApi, genCodeByTablesApi} from "@/api/generate";
import {downloadFile, getFileNameFromDisposition} from "@/utils/common-utils.ts";

const router = useRouter();

// 分页
const page = ref<Page>({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})
/**
 * 数据库切换
 */
const dbKey = ref('')
const dbOptions = ref<GlobalDataSource[]>([]);
const switchDataSource = () => {
  localStorage.setItem(DB_HEADER.DATA_SOURCE_HEADER, dbKey.value)
  findAllTables(page.value)
}
/**
 * 获取数据库表
 */
const tables = ref<DbTable[]>([]);
const tableInfo = ref<ColumnInfo[]>([]);
const findAllTables = (page: Page) => {
  findAllTablesApi(page)
      .then(res => {
        console.log(res)
        tables.value = res.data
        page.total = res.total;
        ElMessage.success("获取数据库表成功")
      })
      .catch(e => {
        console.log('获取数据库表失败')
        ElMessage.error("获取数据库表失败")
      });
}
// 处理页码变化
const handleCurrentChange = (newPage: number) => {
  page.value.pageNum = newPage;
  findAllTables(page.value);
};

// 处理每页条数变化
const handleSizeChange = (newSize: number) => {
  page.value.pageSize = newSize;
  page.value.pageNum = 1; // 重置到第一页
  findAllTables(page.value);
};
/**
 * @Description: 单表生成代码
 * @Author: sxgan
 * @Date: 2025/8/28 16:31
 * @Version: 1.0
 **/
// 生成代码逻辑
const centerDialogVisible = ref(false)
const columnDatas = ref<Array<ColumnInfo>>([]);
const genTable = ref<DbTable>();
const genCode = (index: number, row: DbTable) => {
  centerDialogVisible.value = true;
  genTable.value = row
  columnDatas.value = row.columnInfos
  console.log(index, row)
}

const genCodeByTable = () => {
  genCodeByTableApi(genTable.value!)
      .then(res => {
        downloadFile(res);
      })
      .catch(e => {
        ElMessage.error("生成异常")
      })
  centerDialogVisible.value = false
}
/**
 * @Description: 多选功能及多选生成代码
 * @Author: sxgan
 * @Date: 2025/8/28 16:31
 * @Version: 1.0
 **/
const selectDatas = ref<DbTable[]>([])
const handleSelectionChange = (val: DbTable[]) => {
  selectDatas.value = val
}

const genTables = () => {
  if (!(selectDatas.value.length > 0)) {
    ElMessage.warning("请选择要生成的表")
    return
  }
  genCodeByTablesApi(selectDatas.value)
      .then(res => {
        downloadFile(res);
      })
      .catch(e => {
        ElMessage.error("生成异常")
      })
}

/**
 * 获取数据库列表
 */
onMounted(() => {
  findSelectDatasourceListApi()
      .then(res => {
        dbOptions.value = res.data
        dbOptions.value.forEach(item => {
          if (item.active) {
            dbKey.value = item.key
          }
        })
      })
      .catch(e => {
        console.log('获取数据库下拉列表失败')
        ElMessage.error("获取数据库下拉列表失败")
      });
  // 获取表列表
  findAllTables(page.value)
})
</script>

<template>
  <div class="db-gen-root">
    <div class="header-box">
      <el-select class="el-sel" v-model="dbKey" placeholder="" @change="switchDataSource">
        <el-option
            v-for="item in dbOptions"
            :key="item.key"
            :label="item.key"
            :value="item.key"
        />
      </el-select>
      <el-button class="el-btn" type="primary" @click="genTables">批量生成</el-button>
    </div>
    <div class="tables-box">
      <!-- 添加外层高度控制容器 -->
      <div class="table-box">
        <el-table border :data="tables" style="width: 100%" height="400"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="60"/>
          <el-table-column type="index" width="60" label="序号"/>
          <el-table-column prop="tableName" label="表名"/>
          <el-table-column prop="tableComment" label="表注释"/>
          <el-table-column fixed="right" label="Operations" width="150" min-width="150">
            <template #default="scope">
              <el-button type="primary" size="small" @click="genCode(scope.$index, scope.row)">
                生成代码
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <div class="pagination-box">
        <el-config-provider :locale="zhCn">
          <el-pagination
              class="pagination-container"
              :current-page="page.pageNum"
              :page-size="page.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="page.total"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </el-config-provider>
      </div>

    </div>
    <el-dialog
        v-model="centerDialogVisible"
        title="代码生成"
        align-center
        width="100rem"
    >
      <el-table border :data="columnDatas" style="width: 100%">
        <el-table-column type="index" width="60" label="序号"/>
        <el-table-column prop="name" label="字段名" width="150"/>
        <el-table-column prop="type" label="字段类型" width="90"/>
        <el-table-column prop="size" label="字段大小" width="60"/>
        <el-table-column prop="javaName" label="Java映射属性名" width="150"/>
        <el-table-column prop="javaType" label="Java类型" width="150"/>
        <el-table-column prop="comment" label="字段注释"/>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="genCodeByTable">
            生成
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.db-gen-root {
  height: 100%;
  width: 100%;

  .header-box {
    height: 5rem;

    .el-sel {
      line-height: 5rem;
      width: 24rem;
    }
    .el-btn{
      line-height: 5rem;
      margin-left: 1rem;
    }
  }

  .tables-box {
    height: calc(100% - 5rem);
    overflow-y: auto;

    .table-box {
      //height: calc(100% - 4rem);
    }

    .pagination-box {
      display: flex;
      flex-direction: column;
      margin: 0.5rem;
      height: 3rem;
    }
  }
}
</style>